﻿using System;
using System.Windows.Forms;
using System.Drawing;
using RLab.Programming;

namespace rlab.presentation
{
    class ScaraObserver : IObserver<ProgrammableEventArgs>, IDisposable
    {
        private RichTextBox _box;
        private IDisposable _unsubscriber;

        private delegate void StringToUnitDelegate( ProgrammableEventArgs value );

        public ScaraObserver( RichTextBox box )
        {
            _box = box;
        }

        public void OnCompleted()
        {
        }

        public void OnError( Exception error )
        {
        }

        public void OnNext( ProgrammableEventArgs value )
        {
            var objarr = new object[] { value };
            if ( !_box.IsDisposed )
            {
                _box.BeginInvoke( new StringToUnitDelegate( Append ), objarr );
            }
        }

        public IDisposable Unsubscriber
        {
            set
            {
                _unsubscriber = value;
            }
        }

        public void Dispose()
        {
            if ( _unsubscriber != null )
            {
                _unsubscriber.Dispose();
            }
        }

        private void Append( object value )
        {
            var arg = value as ProgrammableEventArgs;

            var msg = "";
            if ( arg.IsConsole )
            {
                msg = ( arg as ProgrammableEventArgs.Console ).Item;
                _box.SelectionColor = Color.Green;
            }
            else if ( arg.IsLog )
            {
                var log = arg as RLab.Programming.ProgrammableEventArgs.Log;
                msg = log.Item2;
                _box.SelectionColor = log.Item1 == 2 ? Color.Red : Color.Blue;
            }                        

            _box.AppendText( msg + "\n" );
            _box.ScrollToCaret();
        }
    }
}
